package org.gnyxy.controller.front;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.gnyxy.constant.JwtClaimsConstant;
import org.gnyxy.context.BaseContext;
import org.gnyxy.dto.UserLoginDTO;
import org.gnyxy.entity.User;
import org.gnyxy.properties.JwtProperties;
import org.gnyxy.result.Result;
import org.gnyxy.service.UserService;
import org.gnyxy.utils.JwtUtil;
import org.gnyxy.vo.UserLoginVO;
import org.gnyxy.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/front/user")
@Slf4j
@Api(tags = "小程序端-用户相关")
public class UserController {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户登录: {}",userLoginDTO.getCode());
        User user = userService.login(userLoginDTO);
        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .authentication(token)
                .build();
        return Result.success(userLoginVO);
    }

    /**
     * 更新资料
     * @param user
     * @return
     */
    @PostMapping("/api/update")
    @ApiOperation("修改用户信息")
//    @CacheEvict(cacheNames = "userCache", key = "#user.id")
    public Result update(@RequestBody User user){
        log.info("修改用户信息: {}",user);
        userService.update(user);
        return Result.success();
    }

    /**
     * 根据id查找用户
     * @param id
     * @return
     */
    @GetMapping("/api/{id}")
    @ApiOperation("根据id查找用户")
//    @Cacheable(cacheNames = "userCache", key = "#id")
    public Result getById(@PathVariable Long id){
        log.info("根据id: {}查找用户",id);
        UserVO userVO = userService.getById(id);
        return Result.success(userVO);
    }

    @GetMapping("/api/userInfo")
    @ApiOperation("查看自己个人信息")
    public Result getUserInfo(){
        Long userId = BaseContext.getCurrentId();
        log.info("查看用户:{}",userId);
        UserVO userVO = userService.getById(userId);
        return Result.success(userVO);
    }
}
